//
//  JYHouseLoanResultViewController.swift
//  JYCalculate
//
//  Created by 何治军 on 2018/10/30.
//  Copyright © 2018 何治军. All rights reserved.
//

import UIKit

class JYHouseLoanResultViewController: JYBaseViewController,UITableViewDataSource,UITableViewDelegate {
    
    
    var caculateDic:Dictionary<String, String>!
    
    /// 数据
    private var dataArray:[JYHouseLoanModel] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = Localized("house-loan-caculate-result");
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        toCaculate()
    }
    
    override func setUpUI() {
        tableview.tableHeaderView = topView
        tableview.register(JYHouseLoanCell.self, forCellReuseIdentifier: "JYHouseLoanCell")
        tableview.dataSource = self
        tableview.delegate = self
        view.addSubview(tableview)
    }
    
    override func setDefaultInfo() {
        for title in ["支付利息","还款总额","贷款总额","按揭年数"] {
            let model = JYHouseLoanModel()
            model.title = title
            self.dataArray.append(model)
        }
        self.tableview.reloadData()
    }
    
    override func setTheLayout() {
        tableview.mas_updateConstraints { (make) in
            make?.left.mas_equalTo()(self.view)
            make?.top.mas_equalTo()(self.view)
            make?.right.mas_equalTo()(self.view)
            make?.bottom.mas_equalTo()(self.view)
        }
    }
    
    /**
     月利率 = 年利率/12
     等额本息每月还款的公式如下：每月还款额=贷款本金×月利率×（1+月利率）还款月数/[（1+月利率）还款月数-1]
     等额本金每月还款的公式如下：每月还款额=贷款本金/贷款期月数+（本金-已归还本金累计额）×月利率
     */
    func toCaculate() {
        if (self.caculateDic == nil) {
            return
        }
        let repaymentType = self.caculateDic["repaymentType"]
        let money = MultiplicationM(self.caculateDic["money"]!, b: "10000").stringValue
        let year = self.caculateDic["year"]
        let rate = DivisionM(self.caculateDic["rate"]!, b: "100").stringValue
        let totleMonth = MultiplicationM(year!, b: "12").stringValue
        let monthRate = DivisionM(rate, b: "12").stringValue
        
        var firstMonthMoneyNumbner = NSDecimalNumber.init(string: "0")
        var totleMoneyNumbner = NSDecimalNumber.init(string: "0")
        var totleInterestNumbner = NSDecimalNumber.init(string: "0")

        if repaymentType == "0" {
            //计算等额本息(每月等额还款)
            let first = MultiplicationM(MultiplicationM(money, b: monthRate).stringValue, b: AdditionM("1", b: monthRate).raising(toPower: (totleMonth as NSString).integerValue).stringValue).stringValue
            let second = SubtractionM(AdditionM("1", b: monthRate).raising(toPower: (totleMonth as NSString).integerValue).stringValue, b: "1").stringValue
            firstMonthMoneyNumbner = DivisionM(first, b: second)
            totleMoneyNumbner = MultiplicationM(firstMonthMoneyNumbner.stringValue, b: totleMonth)
            totleInterestNumbner = SubtractionM(totleMoneyNumbner.stringValue, b: money)
        }else{
            //计算等额本金(每月递减还款)
            var lastMoney = NSDecimalNumber.init(string: money)//剩余未还本金
            let first = DivisionM(money, b: totleMonth).stringValue //每月要还的本金
            let second = MultiplicationM(money, b: monthRate).stringValue//首月利息
            firstMonthMoneyNumbner = AdditionM(first, b: second)
            for index in 0..<(totleMonth as NSString).integerValue {
                //当月所还金额
                let currentMoney = AdditionM(first, b: MultiplicationM(lastMoney.stringValue, b: monthRate).stringValue)
                totleMoneyNumbner = AdditionM(totleMoneyNumbner.stringValue, b: currentMoney.stringValue)
                lastMoney = SubtractionM(lastMoney.stringValue, b: SubtractionM(first, b: "\(index)").stringValue)
            }
            totleInterestNumbner = SubtractionM(totleMoneyNumbner.stringValue, b: money)
        }
        
        let model = JYHouseLoanModel()
        model.title = "首月还款:(元)"
        model.descri = NTSWithDigit(firstMonthMoneyNumbner, digit: 2)
        self.topView.model = model
        self.dataArray[0].descri = "\(NTSWithDigit(totleInterestNumbner, digit: 2))元"
        self.dataArray[1].descri = "\(NTSWithDigit(DivisionM(totleMoneyNumbner.stringValue, b: "10000"), digit: 2))万"
        self.dataArray[2].descri = "\(self.caculateDic["money"]! as String)万"
        self.dataArray[3].descri = "\(year!)年(\((year! as NSString).integerValue * 12))个月"

        self.tableview.reloadData()
    }
    
    
    //MARK: - UITableViewDataSource,UITableViewDelegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = JYHouseLoanCell.init(style: .default, reuseIdentifier: "JYHouseLoanCell")
        cell.model = self.dataArray[indexPath.row]
        cell.selectionStyle = .none
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44
    }
    // MARK: - 懒加载b
    private lazy var tableview:UITableView = {
        let tab = UITableView()
        tab.separatorStyle = .none
        tab.backgroundColor = JYVCBackGroundColor
        return tab
    }()
    
    private lazy var topView:JYHouseLoanResultTopView = {
        let v = JYHouseLoanResultTopView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        return v
    }()
    
}

class JYHouseLoanResultTopView: JYBaseView {
    
    var model:JYHouseLoanModel = JYHouseLoanModel() {
        didSet{
            self.titleLab.text = model.title
            self.contentLab.text = model.descri
        }
    }
    
    override func setUpUI() {
        super.setUpUI()
        self.addSubview(titleLab)
        self.addSubview(contentLab)
        self.topLine.isHidden = false
    }
    
    override func setTheConstraints() {
        super.setTheConstraints()
        titleLab.mas_updateConstraints { (make) in
            make?.left.mas_equalTo()(self)?.offset()(16)
            make?.top.mas_equalTo()(self)?.offset()(16)
        }
        contentLab.mas_updateConstraints { (make) in
            make?.centerX.mas_equalTo()(self)
            make?.left.mas_lessThanOrEqualTo()(self)?.offset()(36)
            make?.top.mas_equalTo()(self.titleLab.mas_bottom)
        }
    }
    lazy var titleLab:UILabel = {
        let lab = UILabel()
        return lab
    }()
    
    lazy var contentLab:UILabel = {
        let lab = UILabel()
        lab.font = UIFont.systemFont(ofSize: 24)
        lab.textColor = JYDetailRedColor
        lab.numberOfLines = 0
        return lab
    }()
}
